package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.BtoECalendarDialog;
import cn.com.winning.ecare.common.Grideviewmenu;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.MyTimeUtil;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.SlidingLayout;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.InnerListView;

/**
 * 门诊医疗费用
 * @author Administrator
 *
 */
public class CostMzSelect extends Activity
{
	private ListView list_sub;
	private ActionSlideExpandableListView list_main;
	private TextView contenttv, item, reference;

	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> listsub = new ArrayList<Map<String, Object>>();
	private List<Object> children = new ArrayList<Object>();

	private Map<String, Object> map_fy = new HashMap<String, Object>();; // 费用统计按收费日期

	MyMainAdapter mainAdapter = null;
	MySubAdapter subAdapter = null;

	private CostMzSelect othis = this;
	MyApplication myApp;

	CustomProgressDialog proDialog;// 加载框
	private ImageButton btnSearch;// 日期选择按钮
	private LinearLayout layout;
	private int height, statusBarHeight;
	private String startDate = "", endDate = "";
	private TextView nametv, tv, price, startDateText, endDateText, zfprice, ybprice;
	private Double totalprice;
	private ImageButton menuButton;
	private String zfje = "0.0", ybje = "0.0", zje = "0.0";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.cost_mzselect);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		myApp.getUserRecords().setUsername(myApp.getAccount());
		myApp.getUserRecords().setModule("CostMzSelect@门诊医疗费用");
		UserRecord.getInstance(myApp.getUserRecords()).init();

		// 获取view
		findView();

		// 获取费用信息
		getCostInfo();

		setListener();

	}

	private void setListener()
	{
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				othis.onBackPressed();
			}
		});
		btnSearch.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				initDateDialog();
			}
		});
		startDateText.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				initDateDialog();
			}
		});
		endDateText.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				initDateDialog();
			}
		});

	}

	private void initDateDialog()
	{
		// TODO Auto-generated method stub
		// 初始化一个自定义的Dialog
		final BtoECalendarDialog dialog = new BtoECalendarDialog(othis, R.style.MyDialog,startDateText.getText().toString(),endDateText.getText().toString());
		// 获取状态栏高度
		Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		statusBarHeight = frame.top;
		Log.i("aaa", "statusBarHeight :" + statusBarHeight);
		// 获取layout高度
		height = layout.getHeight();
		dialog.show();
		Window mWindow = dialog.getWindow();
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		WindowManager.LayoutParams lp = mWindow.getAttributes();
		lp.x = 0;
		lp.y = height + statusBarHeight;
		lp.width = (int) (display.getWidth()); // 设置宽度
		lp.height = (int) (display.getHeight()) - height - statusBarHeight;// 设置高度
		mWindow.setAttributes(lp);

		Button btnok = (Button) dialog.findViewById(R.id.btnok);
		Button btncancel = (Button) dialog.findViewById(R.id.btncancel);

		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				// 选择开始日期
				TextView startDates = (TextView) dialog.findViewById(R.id.tvSelectedstart);
				// 选择结束日期
				TextView endDates = (TextView) dialog.findViewById(R.id.tvSelectedend);
				String sd = startDates.getText().toString();
				String ed = endDates.getText().toString();

				dialog.dismiss();

				startDate = sd;
				endDate = ed;
				startDateText.setText(startDate);
				endDateText.setText(endDate);
				getCostInfo();

			}
		});

		btncancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

	private void getCostInfo()
	{
		proDialog = CustomProgressDialog.createDialog(othis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadCostInfo()).start();
	}

	class LoadCostInfo implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniCostInfo();
			Looper.loop();
		}
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(othis, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
					if (mainAdapter != null)
					{
						mainAdapter.notifyDataSetChanged();
					}
					break;
				case 1:
					
					price.setText("总费用：" + String.format("%.2f", totalprice));
					ybprice.setText("结算(自费：" + String.format("%.2f", Double.valueOf(zfje)) + "  已纳入统筹："
							+ String.format("%.2f", Double.valueOf(ybje)) + ")");
					proDialog.dismiss();
					mainAdapter = new MyMainAdapter();
					mainAdapter.notifyDataSetChanged();
					list_main.setAdapter(mainAdapter);
					break;

				default:
					break;
			}
		};
	};

	private void iniCostInfo()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
			listmain.clear();
			children.clear();
			Intent intent = getIntent();
			String startDate1 = startDate.replace("-", "").replace("-", "");
			String endDate1 = endDate.replace("-", "").replace("-", "");
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApp.getAccount()));
			ls.add(new BasicNameValuePair("sfzh", myApp.getSfzh()));
			ls.add(new BasicNameValuePair("zsxm",myApp.getHzxm()));
			ls.add(new BasicNameValuePair("sjh",myApp.getSjh()));
			ls.add(new BasicNameValuePair("startdate", startDate1));
			ls.add(new BasicNameValuePair("enddate", endDate1));
			ls.add(new BasicNameValuePair("sfdxmid", ""));
			JSONObject jsoncost = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLCOSTMZ, ls);
			JSONArray jsonArr;
			if (jsoncost != null && !jsoncost.equals(""))
			{
				if (!jsoncost.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (new JSONArray(jsoncost.getString("jsonstr")).length() > 0)
					{
						
						// 医保费用/自费费用/总费用
						if (new JSONArray(jsoncost.getString("ybjsonstr")).length() > 0)
						{
							JSONArray mainjsonArr = new JSONArray(jsoncost.getString("ybjsonstr"));
							JSONObject objje = mainjsonArr.getJSONObject(0);
							zje = objje.getString("zje") == null ? "0.0" : objje.getString("zje").toString();
							ybje = objje.getString("ybje") == null ? "0.0" : objje.getString("ybje").toString();
							zfje = objje.getString("zfje") == null ? "0.0" : objje.getString("zfje").toString();

						}
						else
						{
							zje = "0.0";
							ybje = "0.0";
							zfje = "0.0";
						}
						// 明细费用
						jsonArr = new JSONArray(jsoncost.getString("jsonstr"));
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
						String sfrq_temp = "", sfrq_tempx = "", sfrq_tempy = "";// 记录收费日期
						String dxmid_temp = "", dxmid_tempx = "";// 记录大项目id
						totalprice = 0.00;
						// ///////////////////////////////////////////////////
						double dxmje = 0.00;// 大项目金额
						double sfrqje = 0.00;// 收费日期金额
						String sfdw = "";
						for (int i = 0; i < jsonArr.length(); i++)
						{
							JSONObject obj_main = jsonArr.getJSONObject(i);

							totalprice += Double.valueOf(obj_main.getString("sfje"));// 总金额
							sfrq_tempx = obj_main.getString("sfrq").toString();
							dxmid_tempx = obj_main.getString("sfdxmid").toString();
							// 封装收费日期-费用
							if (sfrq_temp.equals(sfrq_tempx))
							{
								sfrqje += Double.valueOf(obj_main.getString("sfje"));
							}
							else
							{
								sfrqje = Double.valueOf(obj_main.getString("sfje"));
							}
							map_fy.put(sfrq_tempx, sfrqje);// 相同收费日期，覆盖
							//
							Map<String, Object> map_sub = new HashMap<String, Object>();
							map_sub.put("sfxxmmc", obj_main.getString("sfxxmmc"));
							map_sub.put("sfsl", obj_main.getString("sfsl"));
							map_sub.put("sfdj", obj_main.getString("sfdj"));
							sfdw = obj_main.has("sfdw")?obj_main.getString("sfdw"):"";//单位
							map_sub.put("sfdw", sfdw);
							if (sfrq_temp.equals(sfrq_tempx) && dxmid_temp.equals(dxmid_tempx))
							{// 大项目id
								list.add(map_sub);
								dxmje += Double.valueOf(obj_main.getString("sfje"));
							}
							else
							{

								if (i > 0)
								{
									JSONObject obj_main_pre = jsonArr.getJSONObject(i - 1);
									Map<String, Object> map_main = new HashMap<String, Object>();
									map_main.put("sfdxmmc", obj_main_pre.getString("sfdxmmc"));
									map_main.put("sfje", dxmje);

									if (sfrq_tempy.equals(sfrq_temp))
									{// 收费日期
										map_main.put("sfrq", "");
									}
									else
									{
										sfrq_tempy = sfrq_temp;
										map_main.put("sfrq", sfrq_tempy);
									}

									listmain.add(map_main);
									children.add(list);
								}
								list = new ArrayList<Map<String, Object>>();
								list.add(map_sub);
								sfrq_temp = sfrq_tempx;
								dxmid_temp = dxmid_tempx;
								dxmje = Double.valueOf(obj_main.getString("sfje"));

							}
							if (i == jsonArr.length() - 1)
							{
								Map<String, Object> map_main = new HashMap<String, Object>();
								map_main.put("sfdxmmc", obj_main.getString("sfdxmmc"));
								map_main.put("sfje", dxmje);
								if (sfrq_tempy.equals(sfrq_tempx))
								{// 收费日期
									map_main.put("sfrq", "");
								}
								else
								{
									map_main.put("sfrq", sfrq_tempx);
								}
								listmain.add(map_main);
								children.add(list);
							}

						}

						bundle.putInt("type", 1);
						bundle.putString("msg", "");
					}
					else
					{
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				}
				else
				{
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}

			}
			else
			{
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}

			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Bundle bundle = new Bundle();
			bundle.putInt("type", -1);
			bundle.putString("msg", e.toString());
			Message msg = myHandler.obtainMessage();
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}
	}

	private void findView()
	{
		// 加载日期控件
		btnSearch = (ImageButton) this.findViewById(R.id.fysearchButton);
		layout = (LinearLayout) this.findViewById(R.id.fylayout);
		list_main = (ActionSlideExpandableListView) findViewById(R.id.list2);
		price = (TextView) this.findViewById(R.id.totalprice);
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		startDateText = (TextView) this.findViewById(R.id.startDateText);
		endDateText = (TextView) this.findViewById(R.id.endDateText);
		ybprice = (TextView) this.findViewById(R.id.ybprice);

		startDate = StringUtil.isEmpty(myApp.getStartDate()) ? MyTimeUtil.GetSysDate(MyTimeUtil.yyyy_MM_dd,
				MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd, new Date()), 0, -1, 0) : myApp.getStartDate();
		endDate = StringUtil.isEmpty(myApp.getEndDate()) ? MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd, new Date()) : myApp
				.getEndDate();
		myApp.setStartDate("");
		myApp.setEndDate("");
		startDateText.setText(startDate);
		endDateText.setText(endDate);

	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class MyMainAdapter extends BaseAdapter
	{

		public int getCount()
		{
			// TODO Auto-generated method stub
			return listmain.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return listmain.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_costmzselect__main, null);

			if (map.get("sfrq").toString().equals(""))
			{
				view.findViewById(R.id.headitem).setVisibility(View.GONE);
			}
			else
			{
				TextView costtime = (TextView) view.findViewById(R.id.costtime);
				String time = map.get("sfrq").toString();
				String sfrqfytj = String.format("%.2f", map_fy.get(time));

				time = time.substring(0, 4) + "-" + time.substring(4, 6) + "-" + time.substring(6, 8);
				costtime.setText(time);
				TextView totalcost = (TextView) view.findViewById(R.id.totalcost);
				totalcost.setText("收费：" + sfrqfytj + "元");
			}

			TextView sfdxmmc = (TextView) view.findViewById(R.id.sfdxmmc);
			TextView sfje = (TextView) view.findViewById(R.id.sfje);
			sfdxmmc.setText(map.get("sfdxmmc").toString());
			sfje.setText(String.format("%.2f", map.get("sfje")));

			InnerListView list_sub = (InnerListView) view.findViewById(R.id.list_costmzselect_sub);
			ScrollView scroll_view = (ScrollView) view.findViewById(R.id.selectscroll_view);
			listsub = (List<Map<String, Object>>) children.get(position);
			subAdapter = new MySubAdapter(othis, listsub);
			list_sub.setAdapter(subAdapter);
			list_sub.setParentScrollView(scroll_view);
			list_sub.setMaxHeight(DisplayUtil.dip2px(othis, 300));
			return view;
		}

	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class MySubAdapter extends BaseAdapter
	{

		Context context;
		List children;

		public MySubAdapter(Context context, List children)
		{
			super();
			this.context = context;
			this.children = children;
		}

		public int getCount()
		{
			// TODO Auto-generated method stub
			return children.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return children.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_costmzselect_sub, null);

			item = (TextView) view.findViewById(R.id.itemmc);
			item.setText(map.get("sfxxmmc").toString());

			contenttv = (TextView) view.findViewById(R.id.contentcost);
			String dw = "";
			if(!map.get("sfdw").toString().trim().equals("")){
				dw = "("+ map.get("sfdw").toString().trim()+")";
			}
			contenttv.setText("X" + map.get("sfsl").toString()+dw);

			reference = (TextView) view.findViewById(R.id.referencerq);
			if (Double.valueOf(map.get("sfsl").toString()) < 0)
			{
				contenttv.setTextColor(Color.RED);
				reference.setTextColor(Color.RED);
			}
			else
			{
				contenttv.setTextColor(Color.BLACK);
				reference.setTextColor(Color.BLACK);
			}
			reference.setText(map.get("sfdj").toString());

			if (position % 2 == 1)
			{
				view.setBackgroundColor(getResources().getColor(R.color.white));
			}
			return view;
		}

	}

}
